//
//  AuditSubmitView.swift
//  ANOA
//
//  Created by 邱仙凯 on 2025/3/14.
//  Copyright © 2025 zwb. All rights reserved.
//

import UIKit


class AuditSubmitView: UIView {
    
    var singleAuditItemH:CGFloat = 90
    var singleSelectPointItemH:CGFloat = 50
    
    
    
    lazy  var auditTextBg: AuditTextBg = {
        let  v = AuditTextBg()
        v.backgroundColor = .white
        v.layer.masksToBounds = true
        v.layer.cornerRadius = 5
        return v
    }()
    lazy var descLab:UILabel = {
        var v = UILabel()
        v.numberOfLines = 0
        v.font = UIFont.systemFont(ofSize: 15)
        return v
    }()
    
    
    var auditselectArr = [AuditBtnBg]()
    func creatAuSelectBtn() -> AuditBtnBg {
        let  v = AuditBtnBg()
        v.backgroundColor = .white
        v.layer.masksToBounds = true
        v.layer.cornerRadius = 5
        return v
    }
    
    var submitBtn:UIButton = {
        var v = UIButton()
        v.layer.cornerRadius = 8
         v.backgroundColor = UIColor(kshex: "#4972F9")
        v.setTitleColor(.white, for: .normal)
        v.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
        return v
    }()
    
    var imageUtil:KSImageSelectUtil?
    var imgArr = [VideoImg]()
    
    
    var chooseUser = [ChooseUsers]()
    var parVc:UIViewController?
    var chooseUserDic = [String:String]()
    var submitClo:(()->())?
    
    
    
    
    private var _alertCover = UIView()
 
   func present() {
       let cover = UIView()
       cover.frame = UIScreen.main.bounds
        cover.backgroundColor = UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 0.35)
        cover.addSubview(self)
       let tap1 = UITapGestureRecognizer()
       tap1.numberOfTapsRequired = 1
       tap1.addTap { [unowned self] _ in
            
           self.dismiss()
        }
      
        cover.addGestureRecognizer(tap1)
  
       self.snp.makeConstraints { make in
           make.left.right.bottom.equalToSuperview()
           make.height.equalTo(contentHH)
       }
     
      
       if let kwindow =  UIApplication.shared.windows.filter({$0.isKeyWindow}).first {
           kwindow.rootViewController?.view.addSubview(cover)
           cover.layoutIfNeeded()
            _alertCover = cover
        }
 
   }
    // 正在显示
    func isShow() -> Bool {
        return _alertCover.superview.isSome
    }

   
   @objc func dismiss() {
       UIView.animate(withDuration: 0.1, delay: 0, options: .curveEaseInOut) {
           self._alertCover.alpha = 0
       } completion: { isCompleted in
           if isCompleted {
               self.removeFromSuperview()
               self._alertCover.removeFromSuperview()
            }
        }
   }
    
    
    
     
    
    convenience init( chooseUser:[ChooseUsers],title: String,appr:AuditProcessAppear? = nil,vc:UIViewController? = nil) {
        self.init(  chooseUser: chooseUser ,vc: vc)
        
    }
    
    init(  chooseUser:[ChooseUsers] ,vc:UIViewController? = nil) {
        super.init(frame:CGRect.zero)
         
        
        self.chooseUser = chooseUser
        self.parVc = vc
        
        setup()
        createView()
    }
    var blackBg:UIView!
    var contentBg:UIView!
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func willMove(toSuperview newSuperview: UIView?) {
        
        if newSuperview.isSome {
            
            UIView.animate(withDuration: 0.1) { //  出现时
                self.contentBg.ks_y = 0
            }
        }
        
    }
  
    let contentHH:CGFloat = KSGlobal.screenH - 180
    func setup() {
    
        
        contentBg = UIView(frame: CGRect(x:0,y:contentHH,width: KSGlobal.screenW,height: contentHH))
        contentBg.isUserInteractionEnabled = true
        contentBg.backgroundColor = Theme.BACKGROUND_COLOR
        addSubview(contentBg)
        
        
    }
    
    
    
    
    fileprivate func createView() {
        
        for i in 0..<self.chooseUser.count {
            let item = self.chooseUser[i]
            let bbt = creatAuSelectBtn()
            bbt.tag = i
            bbt.btn.addTouchUpInSideAction { bbtbtn in
                
                
                KSNetwork.shared.doRequest(API.auditFlow(.WflowgetStaffName(page: "1", size: "10000", c_name: "", org_name: ""))) { (data:BaseResult<ToDoPerson>) in
                    if data.flag == TRUE {
                        if let infos = data.infoArrCombine {
                            var allArr = [(ToDoPerson,Bool)]()
                            for i in 0..<infos.count {
                                allArr.append((infos[i],false))
                            }
                            let cle:([Any])->() = { arr in
                                let nmarr = arr.compactMap{ ($0 as! ToDoPerson).c_name }.joined(separator: ",")
                                bbtbtn.setTitle(nmarr, for: .normal)
                                let idarr = arr.compactMap{ ($0 as! ToDoPerson).id_key }.joined(separator: ",")
                                
                                let nodeid = self.chooseUser[bbtbtn.tag].nodeId.unwrap
                                self.chooseUserDic.updateValue(idarr, forKey: nodeid)
                                
                                
                                
                            }
                            let showC:((GlobalTableViewCell, Any) -> ()) = { cell, model in
                                var contArr:[(String,String?)]!
                                contArr = [
                                    ("","\((model as! ToDoPerson).c_name.unwrap)")
                                ]
                                cell.setDataSource(contentArr: contArr)
                            }
                            let filterC:((Any, String) -> (Bool)) = { model, keyword -> Bool in
                                return (model as! ToDoPerson).c_name.unwrap.contains(keyword)
                            }
                            let vc = KSMultiSelectUtil.initWithNav(title: "选择", allArr: allArr, backClosure: cle,kSShowCell: showC , filterClosure: filterC)
                            let topViewController = RouterUtils.currentTopViewController()
                            topViewController!.present_FullScreen(to: vc)
                            
                        }
                    } else {
                        KSToast(data.errorCombine.unwrap)
                    }
                }
              
                
            }
            
            bbt.audittextTip.text = item.nodeName
            auditselectArr.append(bbt)
            
            
            
        }
        
        
        
        self.backgroundColor = UIColor(kshex:"#f5f5f5")
        
        
        
        contentBg.addSubview(descLab)

        contentBg.addSubview(auditTextBg)
        
        for item in auditselectArr {
            contentBg.addSubview(item)
        }
        
        imageUtil = KSImageSelectUtil(frame: CGRect(x:0,y:0,width:KSGlobal.screenW - 20 ,height:singleImgHeight * 2),httpHeader: USERINFO.picUrl.unwrap,numberOfRow: 5,viewType: .editable)
        imageUtil!.ksDelegate = self
        contentBg.addSubview(imageUtil!)
        
        
        
        contentBg.addSubview(submitBtn)
     
        submitBtn.snp.makeConstraints { make in
            make.width.equalTo(200)
            make.height.equalTo(38)
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-50)
        }
        
        
        self.makeConstra()
        
    }
 
    
    // 布局
    func makeConstra() {
        descLab.snp.makeConstraints { (make) in
             make.left.equalToSuperview().offset(5)
            make.right.equalToSuperview().offset(-5)
             make.top.equalToSuperview().offset(10)
        }
        auditTextBg.snp.makeConstraints { (make) in
            make.height.equalTo(singleAuditItemH)
            make.left.equalToSuperview().offset(5)
            make.right.equalToSuperview().offset(-5)
            make.top.equalTo(descLab.snp.bottom).offset(10)
        }
    
        
        imageUtil!.snp.remakeConstraints { (make) in
            make.height.equalTo(singleImgHeight * 2)
            make.left.equalToSuperview().offset(5)
            make.right.equalToSuperview().offset(-5)
            make.top.equalTo(auditTextBg.snp.bottom).offset(10)
        }
        
       
        
        let deArr = auditselectArr
        
        for i in 0..<deArr.count {
            let onex = deArr[i]
            onex.snp.makeConstraints { (make) in
                make.height.equalTo(singleSelectPointItemH)
                make.left.equalToSuperview().offset(5)
                make.right.equalToSuperview().offset(-5)
                if i == 0 {
                    make.top.equalTo(self.imageUtil!.snp.bottom).offset(5)
                } else {
                    make.top.equalTo(deArr[i - 1].snp.bottom).offset(5)
                }
                
            }
        }
        
         
    }
    
}

extension AuditSubmitView:KSImageUtilDelegate {
    
    func addImages(_ util:KSImageSelectUtil, imgvideos:[VideoImg]) {
        self.imgArr += imgvideos
        
    }
    
    func deleteImage(_ util: KSImageSelectUtil, index: Int) {
        self.imgArr.remove(at: index)
        self.imageUtil!.deleteLocalImg(tag: index)
    }
    
}

